<?php
/*************************************************************************************
   Copyright notice

   This script uses some code parts of the glossary module for phpwcms (c) Oliver Georgi
   (c) 2002-2009 Oliver Georgi (oliver@phpwcms.de) // All rights reserved.

   This script uses some code parts from bmcatalog module
   (c) 2010 Benjamin Matzmorr, www.etype.de

   (c) 2012 webrealisierung gmbh, www.webrealisierung.ch
   Catalogue Module V 1.0.0  -  Date: 2012-06-01

   The GNU General Public License can be found at http://www.gnu.org/copyleft/gpl.html
   A copy is found in the textfile GPL.txt and important notices to the license
   from the author is found in LICENSE.txt distributed with these scripts.

   This script is distributed in the hope that it will be useful, but WITHOUT ANY
   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
   PARTICULAR PURPOSE.  See the GNU General Public License for more details.

   This copyright notice MUST APPEAR in all copies of the script!
*************************************************************************************/
// ----------------------------------------------------------------
// obligate check for phpwcms constants
if (!defined('PHPWCMS_ROOT')) {
   die("You Cannot Access This Script Directly, Have a Nice Day.");
}
// ----------------------------------------------------------------

// Catalogue module content part frontend article rendering
// if you want to access module vars check that var
// $phpwcms['modules'][$crow["acontent_module"]]

//specific functions for the frontend
 function ctg_combinedParser($string, $charset='utf-8', $allowed_tags='') {

	$string = html_parser($string);
	$string = clean_replacement_tags($string, $allowed_tags);

	$string = str_replace('&nbsp;', ' ', $string);

	$string = decode_entities($string);
	$string = cleanUpSpecialHtmlEntities($string);

	if(!empty($string) && PHPWCMS_CHARSET != $charset) {
		$string = makeCharsetConversion($string, PHPWCMS_CHARSET, $charset);
	} else {
		$string = html_specialchars($string);
	}

	return $string;
}

//function build_filter(cp-id, what html-tag to render, # of filter, content of filter from cp, $_POST, $_GET, $_SESSION, default-value, rel. link-url='')
function build_filter($cpid, $tag, $filter, $cp, $p, $g, $s, $default="default", $lnk='') {

  $mod_ctg_fltr[$filter]['sql'] = "";
  $mod_ctg_fltr[$filter]['listing'] = "";
  $mod_ctg_fltr[$filter]['postvars'] = "";
  $mod_ctg_fltr[$filter]['tags'] = array();

  if ($filter > 0) {
    $mod_ctg_a = explode(",", trim($cp) );
    $mod_ctg_a = array_unique( array_filter( array_map('trim', $mod_ctg_a) ) );
  } else {
    $mod_ctg_a = $cp; //filter0
  }

  if( count($mod_ctg_a) ) {

    //POST and GET and SESSION
    if (!isset($p) || !$p) {
      if 	(!isset($g) || !$g) {
        if 	(!isset($s)) {
      		$mod_ctg_fltr[$filter]['postvars'] = "";
        } else {
          $mod_ctg_fltr[$filter]['postvars'] = rawurldecode($s);
      	  $mod_ctg_fltr[$filter]['postvars'] = clean_slweg($mod_ctg_fltr[$filter]['postvars']);
      	  $mod_ctg_fltr[$filter]['postvars'] = clean_replacement_tags($mod_ctg_fltr[$filter]['postvars']);
      	  $mod_ctg_fltr[$filter]['postvars'] = cleanUpSpecialHtmlEntities($mod_ctg_fltr[$filter]['postvars']);
          $_SESSION['br_catalogue'][$cpid][$filter] = $mod_ctg_fltr[$filter]['postvars'];
        }
      } else {
    		$mod_ctg_fltr[$filter]['postvars'] = rawurldecode($g);
      	$mod_ctg_fltr[$filter]['postvars'] = clean_slweg($mod_ctg_fltr[$filter]['postvars']);
      	$mod_ctg_fltr[$filter]['postvars'] = clean_replacement_tags($mod_ctg_fltr[$filter]['postvars']);
      	$mod_ctg_fltr[$filter]['postvars'] = cleanUpSpecialHtmlEntities($mod_ctg_fltr[$filter]['postvars']);
        $_SESSION['br_catalogue'][$cpid][$filter] = $mod_ctg_fltr[$filter]['postvars'];
    	}
    } else {
    	  $mod_ctg_fltr[$filter]['postvars'] = clean_slweg($p);
      	$mod_ctg_fltr[$filter]['postvars'] = clean_replacement_tags($mod_ctg_fltr[$filter]['postvars']);
      	$mod_ctg_fltr[$filter]['postvars'] = cleanUpSpecialHtmlEntities($mod_ctg_fltr[$filter]['postvars']);
        $_SESSION['br_catalogue'][$cpid][$filter] = $mod_ctg_fltr[$filter]['postvars'];
    }
    if ($filter > 0) {
      //build filter array
      $tmp_array = array();
      foreach($mod_ctg_a as $key => $val) {
        $tmp_array[$key]['id'] = $val;
        $tmp_array[$key]['name'] = $val;
        $tmp_array[$key]['entries'] = array();
      }
    //check postvar against array from CP, only when existing tag filter remains
    if ( !in_array($mod_ctg_fltr[$filter]['postvars'], $mod_ctg_a) ) {
      $mod_ctg_fltr[$filter]['postvars'] = "";
      unset($_SESSION['br_catalogue'][$cpid][$filter]);
    }
    } else { //filter0
      //build filter array
      $tmp_array = array();
      foreach($mod_ctg_a as $key => $val) {
        $tmp_array[$key]['id'] = $val['ctgc_id'];
        $tmp_array[$key]['name'] = $val['ctgc_name'];
        $tmp_array[$key]['entries'] = array();
      }
    }

    $mod_ctg_fltr[$filter]['tags'] = $tmp_array;
    //check postvar against array from CP, only when existing tag filter remains
    if ( $mod_ctg_fltr[$filter]['postvars'] == 'dflt' ) {
      $mod_ctg_fltr[$filter]['postvars'] = "";
      unset($_SESSION['br_catalogue'][$cpid][$filter]);
    }

    //render select output
    if ($tag == 'sel') {

      $mod_ctg_listing = '';
      $mod_ctg_listing  .= LF.'  <option value="dflt">'.$default.'</option>'.LF;
      foreach($mod_ctg_fltr[$filter]['tags'] as $value) {

            $mod_ctg_listing  .= '  <option value="'.$value['id'].'"';
            if ( $value['id']== $mod_ctg_fltr[$filter]['postvars'] ) {
              $mod_ctg_listing  .= ' selected="selected"';
            }
    				$mod_ctg_listing .= '>'.htmlspecialchars($value['name']);
            $mod_ctg_listing .= '</option>'.LF;

      }
      $mod_ctg_fltr[$filter]['listing'] = '<select name="filter'.$filter.'"  onchange="ctgfilterform.submit()">'.$mod_ctg_listing.'</select>';

    } elseif ($tag == 'ul') { //render ul output

      $mod_ctg_listing = '';
      $mod_ctg_listing  .= LF.'  <li class="ctg_menu_ul_all"><a href="'.$lnk.'&amp;filter'.$filter.'=dflt">'.$default.'</a></li>'.LF;
      foreach($mod_ctg_fltr[$filter]['tags'] as $value) {

            $mod_ctg_listing  .= '  <li class="';
            if ( $value['id']== $mod_ctg_fltr[$filter]['postvars'] ) {
              $mod_ctg_listing  .= 'ctg_menu_ul_active';
            }
    				$mod_ctg_listing .= '"><a href="'.$lnk.'&amp;filter'.$filter.'='.rawurlencode($value['id']).'">'.htmlspecialchars($value['name']);
            $mod_ctg_listing .= '</a></li>'.LF;

      }
      $mod_ctg_fltr[$filter]['listing'] = '<ul class="ctg_menu_ul">'.$mod_ctg_listing.'</ul>';

    }

    //render sql
    if ($filter > 0) {
      if ($mod_ctg_fltr[$filter]['postvars'] && $mod_ctg_fltr[$filter]['postvars'] != 'dflt') {
        $mod_ctg_fltr[$filter]['sql'] = " AND ctge_tags LIKE '%|".aporeplace($mod_ctg_fltr[$filter]['postvars'])."|%' ";
      }
    } else { //filter0
      if ($mod_ctg_fltr[$filter]['postvars'] && $mod_ctg_fltr[$filter]['postvars'] != 'dflt') {
        $mod_ctg_fltr[$filter]['sql'] = " AND ctge_catalogid LIKE '%|".aporeplace($mod_ctg_fltr[$filter]['postvars'])."|%' ";
      }
    }

  } //end if filter_1

  //how should be the output
  $mod_ctg_fltr[$filter]['render'] = $tag;
  //add array for FILTER_TAGS RT
  $mod_ctg_fltr[$filter]['array'] = $mod_ctg_a;

return $mod_ctg_fltr[$filter];

}


/*
$plugin
array to store all variables opend while the execution of the script

$plugin['br_catalogue']...
to work with in this script

$plugin['head']...
is added to the head section
*/
//initvars
  //$plugin = array(); already declared in backend.default.php
  $plugin['br_catalogue'] = array();

//open reference to header block
  $plugin['head'] = & $GLOBALS['block']['custom_htmlhead'];

  $plugin['br_catalogue']['map'] = "";
  $plugin['br_catalogue']['postvars'] = array();
  $plugin['br_catalogue']['googlejscode'] = "";
  $plugin['br_catalogue']['googlemarkercode'] = "";
  $plugin['br_catalogue']['query_search'] = "";
  $plugin['br_catalogue']['no_entry'] = false;
  $plugin['br_catalogue']['filter'] = array();
  $plugin['br_catalogue']['list'] = "";
  $plug_cpid = 'fltr'.$crow['acontent_id'];  //the actual cp id to make session unique
/*
$content['br_catalogue'] only contains the values from the cp
all other variables in the script see $plugin['br_catalogue']...
*/
//get contentpart settings
  $content['br_catalogue'] = @unserialize($crow['acontent_form']);


//load template
//template changer
  $plugin['br_catalogue']['postvars']['tmpl'] = '';
  //POST and GET
  if (!isset($_POST['ctgtmpl']) || !$_POST['ctgtmpl']) {
    if 	(!isset($_GET['ctgtmpl']) || !$_GET['ctgtmpl']) {
    } else {
  		$plugin['br_catalogue']['postvars']['tmpl'] = intval($_GET['ctgtmpl']);
  	}
  } else {
  	$plugin['br_catalogue']['postvars']['tmpl'] = intval($_POST['ctgtmpl']);
  }

  // check for template and load default in case of error
  if(empty($content['br_catalogue']['ctg_tmpl'])) {

  	// load default template
    $plugin['br_catalogue']['tmpl']['template'] = file_get_contents($phpwcms['modules'][$crow["acontent_module"]]['path'].'template/default/default.tmpl');

  } elseif(@file_exists($phpwcms['modules'][$crow["acontent_module"]]['path'].'template/cntpart/'.$plugin['br_catalogue']['postvars']['tmpl'].$content['br_catalogue']['ctg_tmpl'])) {

  	// load custom template (defined in contentpart-setup)
  	$plugin['br_catalogue']['tmpl']['template'] = file_get_contents($phpwcms['modules'][$crow["acontent_module"]]['path'].'template/cntpart/'.$plugin['br_catalogue']['postvars']['tmpl'].$content['br_catalogue']['ctg_tmpl']);

  } elseif(@file_exists($phpwcms['modules'][$crow["acontent_module"]]['path'].'template/cntpart/'.$content['br_catalogue']['ctg_tmpl'])) {

  	// load custom template (defined in contentpart-setup)
  	$plugin['br_catalogue']['tmpl']['template'] = file_get_contents($phpwcms['modules'][$crow["acontent_module"]]['path'].'template/cntpart/'.$content['br_catalogue']['ctg_tmpl']);

  } else {

  	// custom template doesnt exist - again load default template
  	$plugin['br_catalogue']['tmpl']['template'] = file_get_contents($phpwcms['modules'][$crow["acontent_module"]]['path'].'template/default/default.tmpl');

  }


//replace values with settings from template - for template >2...
if ( $plugin['br_catalogue']['postvars']['tmpl'] >= 2 ){
	// get template based config and merge with defaults
	$content['br_catalogue']	= array_merge(	$content['br_catalogue'],
									parse_ini_str( get_tmpl_section('TMPL_SETTINGS', 	$plugin['br_catalogue']['tmpl']['template']), false )
								  );
}

//include rss
  if($content['br_catalogue']['ctg_rss_active']== 1 ){
    $plugin["head"]["ctgFeed"] = '<link rel="alternate" type="application/rss+xml" title="Feed Catalog phpwcms" href="'.PHPWCMS_URL.CONTENT_PATH.'rss/feed-catalog-'.$crow["acontent_aid"].'-'.$crow['acontent_id'].'.xml" />';
  }

//get all catalogs - SELECTED in CP AND ACTIVE in DB
  $plugin['br_catalogue']['tmp_catalog']['sql']  = "SELECT * FROM ".DB_PREPEND."phpwcms_mod_catalogue_catalog  WHERE ctgc_status = 1 ORDER BY ctgc_name";
	$plugin['br_catalogue']['tmp_catalog']['data'] = _dbQuery($plugin['br_catalogue']['tmp_catalog']['sql']);
  $plugin['br_catalogue']['tmp_catalog']['active']  = array();
  $plugin['br_catalogue']['tmp_catalog']['activeid']  = array();
	  foreach($plugin['br_catalogue']['tmp_catalog']['data'] as $value) {
      if (in_array($value['ctgc_id'], $content['br_catalogue']['ctg_catalogs'])) {
        array_push($plugin['br_catalogue']['tmp_catalog']['activeid'], $value['ctgc_id']);
        array_push($plugin['br_catalogue']['tmp_catalog']['active'], $value);
      }
    }
  $plugin['br_catalogue']['act_catalogs_id'] = $plugin['br_catalogue']['tmp_catalog']['activeid']; //only id's
  $plugin['br_catalogue']['act_catalogs'] = $plugin['br_catalogue']['tmp_catalog']['active']; //all infos
  

//if no active catalog then abort
if (!empty($plugin['br_catalogue']['act_catalogs_id'])) {

  //prepare sql for different catalogs
  $plugin['br_catalogue']['tmp_catalog']['query'] = array();
  foreach($plugin['br_catalogue']['act_catalogs_id'] as $value) {
		$plugin['br_catalogue']['tmp_catalog']['query'][] = "ctge_catalogid LIKE '%|".aporeplace(intval($value))."|%'";
	}
	$plugin['br_catalogue']['query_catalogs'] = (count($plugin['br_catalogue']['tmp_catalog']['query'])) ? " AND (".implode(' OR ', $plugin['br_catalogue']['tmp_catalog']['query']).")" : " AND ctge_allcats = 'default'"; //or never true

  unset($plugin['br_catalogue']['tmp_catalog']);

//get all tags in entries within given catalogs
  //ctge_tags = tags
   $plugin['br_catalogue']['tmp_tags']['sql'] = "SELECT ctge_tags FROM " . DB_PREPEND . "phpwcms_mod_catalogue_entry WHERE ctge_tags > '' AND ctge_status=1";
   $plugin['br_catalogue']['tmp_tags']['sql'] .= $plugin['br_catalogue']['query_catalogs'];
   $plugin['br_catalogue']['tmp_tags']['sql'] .= " GROUP BY ctge_tags ORDER BY ctge_tags";
   $plugin['br_catalogue']['tmp_tags']['data'] = _dbQuery( $plugin['br_catalogue']['tmp_tags']['sql']);
  //build string and array with result, only unique values
   $plugin['br_catalogue']['tmp_tags']['all'] = array();
  if ( count( $plugin['br_catalogue']['tmp_tags']['data']) > 0 ) {
    foreach ( $plugin['br_catalogue']['tmp_tags']['data'] as $row) {
       $plugin['br_catalogue']['tmp_tags']['arr'] = explode("|", trim($row["ctge_tags"], "|") );
       $plugin['br_catalogue']['tmp_tags']['all'] = array_merge( $plugin['br_catalogue']['tmp_tags']['all'], array_map('trim',  $plugin['br_catalogue']['tmp_tags']['arr']));
    }
  }
  $plugin['br_catalogue']['tags_string'] = '"' . implode( '", "', array_unique( $plugin['br_catalogue']['tmp_tags']['all'])) . '"';
  $plugin['br_catalogue']['tags'] = array_unique( $plugin['br_catalogue']['tmp_tags']['all']);

  unset($plugin['br_catalogue']['tmp_tags']);

//check for jslib
  $plugin['br_catalogue']['jslib'] = ( strpos($GLOBALS["block"]["jslib"], 'jquery') !== false ) ? "jquery" : "mootools" ;

  if ($plugin['br_catalogue']['jslib']=="mootools") {
  	initJSLib();								//Init JS
  	$mootools_more = array( 'Fx/Fx.Slide' );  	// Loading more and FX.Slide lib
  	initJSPlugin($mootools_more, true);
  }


//load google maps api ?
  if ($content['br_catalogue']['ctg_usegooglemaps']) {
  	$plugin['head']['googleapi'] =  '<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> ';
  	include ($phpwcms['modules'][$crow["acontent_module"]]['path'].'inc/googlemapsapi.php');
  }


//load module css
  if(isset($content['br_catalogue']['ctg_css']) && @file_exists($phpwcms['modules'][$crow['acontent_module']]['path'].'template/css/'.$content['br_catalogue']['ctg_css'])) {
    $plugin['head']['catalog.css'] = '<link rel="stylesheet" type="text/css" href="'.PHPWCMS_URL.$phpwcms['modules'][$crow["acontent_module"]]['dir'].'template/css/'.$content['br_catalogue']['ctg_css'].'" />';
  }


// is width/height set in cp-settings? else use phpwcms standard list sizes - Images for Listings
  $content['br_catalogue']['ctg_imgwidth'] = ($content['br_catalogue']['ctg_imgwidth']==0   || isempty($content['br_catalogue']['ctg_imgwidth']))  ? ""  : intval($content['br_catalogue']['ctg_imgwidth']);
  $content['br_catalogue']['ctg_imgheight'] = ($content['br_catalogue']['ctg_imgheight']==0 || isempty($content['br_catalogue']['ctg_imgheight'])) ? "" : intval($content['br_catalogue']['ctg_imgheight']);
  if ( empty($content['br_catalogue']['ctg_imgwidth']) && empty($content['br_catalogue']['ctg_imgheight']) ) {
    $content['br_catalogue']['ctg_imgwidth'] = $phpwcms['img_list_width'];
    $content['br_catalogue']['ctg_imgheight'] = $phpwcms['img_list_height'];
  }



//build baselink
  //tmpl changer
  $lnktmpl = "";
  if ( $plugin['br_catalogue']['postvars']['tmpl'] ){
    $lnktmpl = "&ctgtmpl=".$plugin['br_catalogue']['postvars']['tmpl'];
  }

  $plugin['br_catalogue']['base_link'] = '';
  //$plugin['br_catalogue']['base_link'] = htmlspecialchars(basename($_SERVER['PHP_SELF'])).returnGlobalGET_QueryString('htmlentities');;
  $plugin['br_catalogue']['base_link'] = basename($_SERVER['PHP_SELF']).'?aid='.$crow["acontent_aid"].$lnktmpl;


//Searchword
  $plugin['br_catalogue']['postvars']['search'] = '';
  //POST and GET
  if (!isset($_POST['ctgsearch']) || !$_POST['ctgsearch']) {
    if 	(!isset($_GET['ctgsearch']) || !$_GET['ctgsearch']) {
    } else {
  		$plugin['br_catalogue']['postvars']['search'] = rawurldecode($_GET['ctgsearch']);
  	}
  } else {
  	$plugin['br_catalogue']['postvars']['search'] = $_POST['ctgsearch'];
  }
	$plugin['br_catalogue']['postvars']['search'] = clean_slweg($plugin['br_catalogue']['postvars']['search']);
	$plugin['br_catalogue']['postvars']['search'] = clean_replacement_tags($plugin['br_catalogue']['postvars']['search']);
	$plugin['br_catalogue']['postvars']['search'] = cleanUpSpecialHtmlEntities($plugin['br_catalogue']['postvars']['search']);

	if ( isset($plugin['br_catalogue']["postvars"]["search"]) && $plugin['br_catalogue']["postvars"]["search"] != '' ) {
		$plugin['br_catalogue']['query_search'] = " AND CONCAT(ctge_title, ctge_title2, ctge_text, ctge_text2, ctge_address_address, ctge_address_city, ctge_address_country) LIKE '%".aporeplace($plugin['br_catalogue']["postvars"]["search"])."%' ";
	}


//filter

  //filter 0 from CP
  $_POST['filter0'] = isset($_POST['filter0']) ? $_POST['filter0'] : "";
  $_GET['filter0'] = isset($_GET['filter0']) ? $_GET['filter0'] : "";
  $_SESSION['br_catalogue'][$plug_cpid][0] = isset($_SESSION['br_catalogue'][$plug_cpid][0]) ? $_SESSION['br_catalogue'][$plug_cpid][0] : "";
  $plugin['br_catalogue']['filter'][0] = build_filter($plug_cpid, $content['br_catalogue']['ctg_fltr0_render'], 0, $plugin['br_catalogue']['act_catalogs'], $_POST['filter0'], $_GET['filter0'], $_SESSION['br_catalogue'][$plug_cpid][0], $content['br_catalogue']['ctg_fltr0_dflt'], $plugin['br_catalogue']['base_link']);

  //filter 1 from CP
  $_POST['filter1'] = isset($_POST['filter1']) ? $_POST['filter1'] : "";
  $_GET['filter1'] = isset($_GET['filter1']) ? $_GET['filter1'] : "";
  $_SESSION['br_catalogue'][$plug_cpid][1] = isset($_SESSION['br_catalogue'][$plug_cpid][1]) ? $_SESSION['br_catalogue'][$plug_cpid][1] : "";
  $plugin['br_catalogue']['filter'][1] = build_filter($plug_cpid, $content['br_catalogue']['ctg_fltr1_render'], 1, $content['br_catalogue']['ctg_filter1'], $_POST['filter1'], $_GET['filter1'], $_SESSION['br_catalogue'][$plug_cpid][1], $content['br_catalogue']['ctg_fltr1_dflt'], $plugin['br_catalogue']['base_link']);

  //filter 2 from CP
  $_POST['filter2'] = isset($_POST['filter2']) ? $_POST['filter2'] : "";
  $_GET['filter2'] = isset($_GET['filter2']) ? $_GET['filter2'] : "";
  $_SESSION['br_catalogue'][$plug_cpid][2] = isset($_SESSION['br_catalogue'][$plug_cpid][2]) ? $_SESSION['br_catalogue'][$plug_cpid][2] : "";
  $plugin['br_catalogue']['filter'][2] = build_filter($plug_cpid, 'sel', 2, $content['br_catalogue']['ctg_filter2'], $_POST['filter2'], $_GET['filter2'], $_SESSION['br_catalogue'][$plug_cpid][2], $content['br_catalogue']['ctg_fltr2_dflt']);

  //filter 3 from CP
  $_POST['filter3'] = isset($_POST['filter3']) ? $_POST['filter3'] : "";
  $_GET['filter3'] = isset($_GET['filter3']) ? $_GET['filter3'] : "";
  $_SESSION['br_catalogue'][$plug_cpid][3] = isset($_SESSION['br_catalogue'][$plug_cpid][3]) ? $_SESSION['br_catalogue'][$plug_cpid][3] : "";
  $plugin['br_catalogue']['filter'][3] = build_filter($plug_cpid, 'sel', 3, $content['br_catalogue']['ctg_filter3'], $_POST['filter3'], $_GET['filter3'], $_SESSION['br_catalogue'][$plug_cpid][3], $content['br_catalogue']['ctg_fltr3_dflt']);

  //filter 4 from CP
  $_POST['filter4'] = isset($_POST['filter4']) ? $_POST['filter4'] : "";
  $_GET['filter4'] = isset($_GET['filter4']) ? $_GET['filter4'] : "";
  $_SESSION['br_catalogue'][$plug_cpid][4] = isset($_SESSION['br_catalogue'][$plug_cpid][4]) ? $_SESSION['br_catalogue'][$plug_cpid][4] : "";
  $plugin['br_catalogue']['filter'][4] = build_filter($plug_cpid, 'sel', 4, $content['br_catalogue']['ctg_filter4'], $_POST['filter4'], $_GET['filter4'], $_SESSION['br_catalogue'][$plug_cpid][4], $content['br_catalogue']['ctg_fltr4_dflt']);

//build a string with all selected filtervalues
  $plugin['br_catalogue']['filterstring'] = array();
    foreach ($plugin['br_catalogue']['filter'] as $value ) {
      if (isset($value['postvars'])) {
        foreach ($value['tags'] as $val ) {
          if ($val['id'] == $value['postvars']) {
            $plugin['br_catalogue']['filterstring'][] = $val['name'];
          }
        }
      }
    }
  $plugin['br_catalogue']['filterstring'] = implode(' - ', $plugin['br_catalogue']['filterstring']);



// ctg_id set ? => details entry
// -------------single entry-------------
  if(!empty($_GET['ctg_id']) && intval($_GET['ctg_id']) ) {

    $plugin['br_catalogue']['ctg_id'] = intval($_GET['ctg_id']);

//is width/height set in cp-settings? else use phpwcms standard list sizes - Images for Detail View
    $content['br_catalogue']['ctg_imgwidth_detail'] = ($content['br_catalogue']['ctg_imgwidth_detail']==0   || isempty($content['br_catalogue']['ctg_imgwidth_detail']))  ? ""  : intval($content['br_catalogue']['ctg_imgwidth_detail']);
    $content['br_catalogue']['ctg_imgheight_detail'] = ($content['br_catalogue']['ctg_imgheight_detail']==0 || isempty($content['br_catalogue']['ctg_imgheight_detail'])) ? "" : intval($content['br_catalogue']['ctg_imgheight_detail']);
    if ( empty($content['br_catalogue']['ctg_imgwidth_detail']) && empty($content['br_catalogue']['ctg_imgwidth_detail']) ) {
      $content['br_catalogue']['ctg_imgwidth_detail'] = $phpwcms['img_list_width'];
      $content['br_catalogue']['ctg_imgheight_detail'] = $phpwcms['img_list_height'];
    }


//get detail entry template sections
  	$plugin['br_catalogue']['tmpl']['detail_head']		= get_tmpl_section('CATALOG_DETAIL_HEAD',		$plugin['br_catalogue']['tmpl']['template']);
  	$plugin['br_catalogue']['tmpl']['detail_footer']		= get_tmpl_section('CATALOG_DETAIL_FOOTER',		$plugin['br_catalogue']['tmpl']['template']);
  	$plugin['br_catalogue']['tmpl']['detail_entry']		= get_tmpl_section('CATALOG_DETAIL_ENTRY',		$plugin['br_catalogue']['tmpl']['template']);
    $plugin['br_catalogue']['tmpl']['detail_images']		= get_tmpl_section('CATALOG_DETAIL_IMAGE',		$plugin['br_catalogue']['tmpl']['template']);
  	$plugin['br_catalogue']['tmpl']['detail_noentry']		= get_tmpl_section('CATALOG_NO_ENTRY',			$plugin['br_catalogue']['tmpl']['template']);

//get singe entry from DB
  	$plugin['br_catalogue']['tmp_entry']['sql']  = 'SELECT * FROM '.DB_PREPEND.'phpwcms_mod_catalogue_entry  WHERE ctge_status=1  ';
  	$plugin['br_catalogue']['tmp_entry']['sql'] .= 'AND ctge_id='.aporeplace($plugin['br_catalogue']['ctg_id']). ' LIMIT 1 ';

  	$plugin['br_catalogue']['tmp_entry']['data'] = @_dbQuery($plugin['br_catalogue']['tmp_entry']['sql']);


  	if(empty($plugin['br_catalogue']['tmp_entry']['data'][0])) {

      $plugin['br_catalogue']['tmpl']['detail_head'] .= $plugin['br_catalogue']['tmpl']['detail_noentry'];
  		$plugin['br_catalogue']['entry']['ctge_title']	= '';
  		$plugin['br_catalogue']['entry']['ctge_id']	= 	'';

  	} else {
  		//take first entry ... there is only one
  		$plugin['br_catalogue']['entry'] = $plugin['br_catalogue']['tmp_entry']['data'][0];

      //unserialize ctge_image
      $plugin['br_catalogue']['entry']['ctge_image'] =	@unserialize($plugin['br_catalogue']['entry']['ctge_image']);

      //unserialize ctge_file
      $plugin['br_catalogue']['entry']['ctge_file'] =	@unserialize($plugin['br_catalogue']['entry']['ctge_file']);
    }

    unset($plugin['br_catalogue']['tmp_entry']);
  

	//get address array - deprected
	//$plugin['br_catalogue']['entry']['address']=	@unserialize($plugin['br_catalogue']['entry']['ctge_address']);

//replace texts
  	$plugin['br_catalogue']['tmpl']['detail_entry']	= get_tmpl_section('CATALOG_DETAIL_ENTRY',		$plugin['br_catalogue']['tmpl']['template']);
  	$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'TEXT', $plugin['br_catalogue']['entry']['ctge_text']);
  	$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'TEXT2', $plugin['br_catalogue']['entry']['ctge_text2']);
  	$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'TITLE', html_entities($plugin['br_catalogue']['entry']['ctge_title']));
  	$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'TITLE2', html_entities($plugin['br_catalogue']['entry']['ctge_title2']));

  	$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'ADDRESS', html_entities($plugin['br_catalogue']['entry']['ctge_address_address']));
  	$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'ZIP', html_entities($plugin['br_catalogue']['entry']['ctge_address_zip']));
  	$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'CITY', html_entities($plugin['br_catalogue']['entry']['ctge_address_city']));
  	$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'COUNTRY', html_entities($plugin['br_catalogue']['entry']['ctge_address_country']));

//replace FILTER_TAGS
    $plugintmp_tags = array();
    $plugintmp_tags = explode("|", trim($plugin['br_catalogue']['entry']["ctge_tags"], "|") );
    for ($i=1;$i<=4 ;$i++ ) {
    	$filtertags1 = array();
      $filtertags1 = array_intersect($plugintmp_tags,$plugin['br_catalogue']['filter'][$i]['array']);
      $plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'FILTER'.$i.'_TAGS', html_entities(implode(', ', $filtertags1)));
    }

//replace download file
  	if (isset( $plugin['br_catalogue']['entry']['ctge_file'][0])) {
  		$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'FILE_URL', 'download.php?f='. $plugin['br_catalogue']['entry']['ctge_file'][2]);
  		$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'FILE_NAME',  $plugin['br_catalogue']['entry']['ctge_file'][1]);
  		$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'FILE_DESC',  $plugin['br_catalogue']['entry']['ctge_file'][6]);
  		$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'FILE_EXT',  $plugin['br_catalogue']['entry']['ctge_file'][3]);
  	} else {
  		$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'FILE_URL', '');
  		$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'FILE_NAME', '');
  		$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'FILE_DESC', '');
  	}


//replace images
    //which gallery?
    if ($plugin['br_catalogue']['entry']['ctge_image'][1]['active'] == 1) { //images from folder

        $list_img_temp = '';
				$img_a = "";

        $ctg_folder_imgs = $plugin['br_catalogue']['entry']['ctge_image'][1];
          /*
          $ctg_folder_imgs['root']
          $ctg_folder_imgs['pag']
          $ctg_folder_imgs['pagnr']
          */
        $plugin['br_catalogue']['tmpl']['detail_list_image'] = "";

  //init slimbox
    		if ($content['br_catalogue']['ctg_imgzoom_detail']) {
          initSlimbox();
        }

        $folder = opendir($phpwcms['modules'][$crow["acontent_module"]]['dir'].$ctg_folder_imgs['root']);

        $pic_types = array("jpg", "jpeg", "gif", "png");
        $pics = array();
        while ($file = readdir ($folder)) {
          if(in_array(substr(strtolower($file), strrpos($file,".") + 1),$pic_types) ) {
            array_push($pics,$file);
          }
        }
        closedir($folder);
        if (count($pics)) {
          if ( $content['br_catalogue']['ctg_imgrand_detail'] ) {
            shuffle($pics);
          }

      $i=0;
      foreach($pics as $val ) {

  				//html image
  				$list_img_temp  = '<img src="'.$phpwcms['modules'][$crow["acontent_module"]]['dir'].$ctg_folder_imgs['root'].'thumbs/tmbdet_'.$crow['acontent_id'].'_'.$val.'" ';
    			//$list_img_temp  .= 'width="'.$content['br_catalogue']['ctg_imgwidth_detail'].'" height="'.$content['br_catalogue']['ctg_imgheight_detail'].'" ';
  				$list_img_temp .= 'alt="" border="0" />';

  				//click to enlarge is set ?
  				if ($content['br_catalogue']['ctg_imgzoom_detail']) {

    				$img_a = '<a href="'.$phpwcms['modules'][$crow["acontent_module"]]['dir'].$ctg_folder_imgs['root'].'/'.$val.'" rel="lightbox['.$plugin['br_catalogue']['entry']['ctge_id'].']"';
    				$img_a .= ' target="_blank">';
            $img_a .= $list_img_temp.'</a>';

          } else {
  					//no zoom
  					$img_a = $list_img_temp;
  				}

  			  //Replace with content
          $plugin['br_catalogue']['tmpl']['detail_entry_image'] = $plugin['br_catalogue']['tmpl']['detail_images'];
  				$plugin['br_catalogue']['tmpl']['detail_entry_image']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry_image'], 'IMAGE', $img_a );
  				$plugin['br_catalogue']['tmpl']['detail_entry_image']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry_image'], 'IMAGE_DESC', "" );

        $plugin['br_catalogue']['tmpl']['detail_list_image'] .= $plugin['br_catalogue']['tmpl']['detail_entry_image'];
        }//foreach-loop
      }
			$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'IMAGES', $plugin['br_catalogue']['tmpl']['detail_list_image'] );


    } else { //phpwcms images

      $ctg_phpwcms_imgs = $plugin['br_catalogue']['entry']['ctge_image'][0];

      $plugin['br_catalogue']['tmpl']['detail_list_image'] = "";

//init slimbox
  		if ($content['br_catalogue']['ctg_imgzoom_detail']) {
        initSlimbox();
      }


      $i=0;
      foreach($ctg_phpwcms_imgs['data'] as $key => $val ) {

  		  if (count($val)) {

  				//build html img-tag
  				$img_a = "";


  				//get image
  				// 0   :1       :2   :3        :4    :5     :6      :7       :8
  				// dbid:filename:hash:extension:width:height:caption:position:zoom
  				$thumb_image = @get_cached_image(
  								array(	"target_ext"	=>	$val['f_ext'],
  										"image_name"	=>	$val['f_hash'] . '.' . $val['f_ext'],
  										"max_width"		=>	$content['br_catalogue']['ctg_imgwidth_detail'],
  										"max_height"	=>	$content['br_catalogue']['ctg_imgheight_detail'],
  										"thumb_name"	=>	md5(	$val['f_hash'].
  																	$content['br_catalogue']['ctg_imgwidth_detail'].
  																	$content['br_catalogue']['ctg_imgheight_detail'].
  																	$phpwcms["sharpen_level"].$content['br_catalogue']['ctg_imgcrop_detail']
  																),
                      "crop_image"    =>    $content['br_catalogue']['ctg_imgcrop_detail']
  									  )
  									);


  				if($thumb_image != false) {

  					//html image
  					$list_img_temp  = '<img src="'.PHPWCMS_IMAGES.$thumb_image[0].'" ';
  					$list_img_temp .= $thumb_image[3].' alt="'.html_specialchars($val['caption']).'" border="0" />';

  					//click to enlarge is set ?
  					if ($content['br_catalogue']['ctg_imgzoom_detail']) {

  						//get full image info

  						$zoom_image = get_cached_image(
  												array(	"target_ext"	=>	$val['f_ext'],
  														"image_name"	=>	$val['f_hash'] . '.' . $val['f_ext'],
  														"max_width"		=>	$phpwcms["img_prev_width"],
  														"max_height"	=>	$phpwcms["img_prev_height"],
  														"thumb_name"	=>	md5(	$val['f_hash'].
  																					$phpwcms["img_prev_width"].
  																					$phpwcms["img_prev_height"].
  																					$phpwcms["sharpen_level"]
  																				)
  													  )
  								);

  						if ($zoom_image != false) {
  						  // if click enlarge the image
  
        				$img_a = '<a href="'.PHPWCMS_IMAGES.$zoom_image[0].'" rel="lightbox['.$plugin['br_catalogue']['entry']['ctge_id'].']"';
        				if($val['caption']) {
        					$img_a .= ' title="'.parseLightboxCaption($val['caption']).'"';
        				}
        				$img_a .= ' target="_blank">';
                $img_a .= $list_img_temp.'</a>';

  						} else {
  								// no big image
  								$img_a = $list_img_temp;
  						}
  					} else {
  						//no zoom
  						$img_a = $list_img_temp;
  					}

  				} //no thumbnail

  			  //Replace with content
          $plugin['br_catalogue']['tmpl']['detail_entry_image'] = $plugin['br_catalogue']['tmpl']['detail_images'];
  				$plugin['br_catalogue']['tmpl']['detail_entry_image']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry_image'], 'IMAGE', $img_a );
  				$plugin['br_catalogue']['tmpl']['detail_entry_image']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry_image'], 'IMAGE_DESC', html_specialchars($val['caption']) );

  		  } else {	// no image, leave empty
    			$plugin['br_catalogue']['tmpl']['detail_entry_image']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry_image'], 'IMAGE', "" );
    			$plugin['br_catalogue']['tmpl']['detail_entry_image']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry_image'], 'IMAGE_DESC', "" );
  		  }

        $plugin['br_catalogue']['tmpl']['detail_list_image'] .= $plugin['br_catalogue']['tmpl']['detail_entry_image'];
        $i++;
      } //foreach-loop

			$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'IMAGES', $plugin['br_catalogue']['tmpl']['detail_list_image'] );
    } //end phpwcms images


//build google maps

  	//Show entry ?
  	if ($plugin['br_catalogue']['entry']['ctge_address_show_map']==1) {

      //if global map api not loaded do it here
      if (!$content['br_catalogue']['ctg_usegooglemaps']) {
        	$plugin['head']['googleapi'] =  '<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> ';
        	include ($phpwcms['modules'][$crow["acontent_module"]]['path'].'inc/googlemapsapi.php');
      }

      //should have coordinates now => add js code
      if ($plugin['br_catalogue']['entry']['ctge_address_long']!=0 && $plugin['br_catalogue']['entry']['ctge_address_lat']!=0)  {
        $plugin['br_catalogue']['googlejscode']=getJSInitCodeGoogleMaps(floatval($plugin['br_catalogue']['entry']['ctge_address_lat']), floatval($plugin['br_catalogue']['entry']['ctge_address_long']), 14);
        //custom image
        if ( isset($plugin['br_catalogue']['entry']['ctge_address_marker']) && $plugin['br_catalogue']['entry']['ctge_address_marker'] != '0.gif' && file_exists($phpwcms['modules'][$crow["acontent_module"]]['path'].'template/map-icons/'.$plugin['br_catalogue']['entry']['ctge_address_marker']) ) {
            $markerimg = PHPWCMS_URL.$phpwcms['modules'][$crow["acontent_module"]]['dir'].'template/map-icons/'.$plugin['br_catalogue']['entry']['ctge_address_marker'];
        } else {
            $markerimg = ""; //takes the google marker
        }
        $plugin['br_catalogue']['googlejscode'].=getJSNewMarkerCode($plugin['br_catalogue']['entry']['ctge_id'], $plugin['br_catalogue']['entry']['ctge_address_long'], $plugin['br_catalogue']['entry']['ctge_address_lat'], html_specialchars($plugin['br_catalogue']['entry']['ctge_title']),$markerimg);
        $content['br_catalogue']['map'] = '<div id="map_canvas" class="mapcontainer_detail">You need to enable javascript in order to user google maps.</div>'.LF.'<script type="text/javascript">'.LF.'<!-- '.$plugin['br_catalogue']['googlejscode'].' //-->'.LF.'</script>'.LF.'<noscript>You need to enable javascript in order to use google maps.</noscript>';
      } else {
        $content['br_catalogue']['map']= "<script type=\"text/javascript\">alert('No coordinates found. Please update entry in backend.');</script>";
      }

  	} //end Show entry in map


//render map contents
  	$plugin['br_catalogue']['tmpl']['detail_entry']	= render_cnt_template($plugin['br_catalogue']['tmpl']['detail_entry'], 'MAP', $content['br_catalogue']['map'] );

//Build it
  	$plugin['br_catalogue']['tmpl']['item'] = $plugin['br_catalogue']['tmpl']['detail_head'] . $plugin['br_catalogue']['tmpl']['detail_entry'] . $plugin['br_catalogue']['tmpl']['detail_footer'];

//Check for placeholder overall
  	$plugin['br_catalogue']['tmpl']['item'] = str_replace('{CATALOG_ID}', $plugin['br_catalogue']['entry']['ctge_id'], $plugin['br_catalogue']['tmpl']['item']);
  	$plugin['br_catalogue']['tmpl']['item'] = str_replace('{BACKLINK}', $plugin['br_catalogue']['base_link'], $plugin['br_catalogue']['tmpl']['item']);
    $plugin['br_catalogue']['tmpl']['item']	= render_cnt_template($plugin['br_catalogue']['tmpl']['item'], 'FILTER_STRING', html_entities($plugin['br_catalogue']['filterstring']));

//display entry
  	$CNT_TMP .= $plugin['br_catalogue']['tmpl']['item'];


  } else {
//-------------listing-------------


// get list entries template sections
	$plugin['br_catalogue']['tmpl']['list_head']            = get_tmpl_section('CATALOG_LIST_HEAD', $plugin['br_catalogue']['tmpl']['template']);
	$plugin['br_catalogue']['tmpl']['list_footer']          = get_tmpl_section('CATALOG_LIST_FOOTER', $plugin['br_catalogue']['tmpl']['template']);
	$plugin['br_catalogue']['tmpl']['list_entry']           = get_tmpl_section('CATALOG_LIST_ENTRY', $plugin['br_catalogue']['tmpl']['template']);
	$plugin['br_catalogue']['tmpl']['list_spacer']          = get_tmpl_section('CATALOG_LIST_SPACER', $plugin['br_catalogue']['tmpl']['template']);
	$plugin['br_catalogue']['tmpl']['list_category_header'] = get_tmpl_section('CATALOG_LIST_CATEGORY_HEADER', $plugin['br_catalogue']['tmpl']['template']);
	$plugin['br_catalogue']['tmpl']['list_category_footer'] = get_tmpl_section('CATALOG_LIST_CATEGORY_FOOTER', $plugin['br_catalogue']['tmpl']['template']);
	$plugin['br_catalogue']['tmpl']['detail_noentry']       = get_tmpl_section('CATALOG_NO_ENTRY', $plugin['br_catalogue']['tmpl']['template']);


//get active catalog entries 
  $plugin['br_catalogue']['tmp_entries']['sql'] = 'SELECT * FROM '.DB_PREPEND.'phpwcms_mod_catalogue_entry WHERE ctge_status=1';
//in given Catalogs
  $plugin['br_catalogue']['tmp_entries']['sql'] .= $plugin['br_catalogue']['query_catalogs'];
//apply all filters
  $plugin['br_catalogue']['tmp_entries']['sql'] .= $plugin['br_catalogue']['filter'][0]['sql'];
  $plugin['br_catalogue']['tmp_entries']['sql'] .= $plugin['br_catalogue']['filter'][1]['sql'];
  $plugin['br_catalogue']['tmp_entries']['sql'] .= $plugin['br_catalogue']['filter'][2]['sql'];
  $plugin['br_catalogue']['tmp_entries']['sql'] .= $plugin['br_catalogue']['filter'][3]['sql'];
  $plugin['br_catalogue']['tmp_entries']['sql'] .= $plugin['br_catalogue']['filter'][4]['sql'];
  $plugin['br_catalogue']['tmp_entries']['sql'] .= $plugin['br_catalogue']['query_search'];
  $plugin['br_catalogue']['tmp_entries']['sql'] .= ' ORDER BY ctge_title';

  $plugin['br_catalogue']['tmp_entries']['data']  = _dbQuery($plugin['br_catalogue']['tmp_entries']['sql']);


//got entries ?
	if( !count($plugin['br_catalogue']['tmp_entries']['data']) ) {

		//Add no entry-template-text
		$plugin['br_catalogue']['tmpl']['list_head'] .= $plugin['br_catalogue']['tmpl']['detail_noentry'];
		$plugin['br_catalogue']['no_entry'] = true;

	} else {

//loop through every entry and replace tags ...
		//save in $plugin['br_catalogue']['entries'][$ekey];
		foreach($plugin['br_catalogue']['tmp_entries']['data'] as $ekey => $evalue) {

      //values from DB
      $plugin['br_catalogue']['entries'][$ekey] = $evalue;

      //ctge_catalogid to array
      $plugin['br_catalogue']['tmp_entries']['ctlg_id'] = $evalue['ctge_catalogid'];
      $plugin['br_catalogue']['tmp_entries']['ctlg_id'] = explode("|", trim($plugin['br_catalogue']['tmp_entries']['ctlg_id']) );
      $plugin['br_catalogue']['tmp_entries']['ctlg_id'] = array_unique( array_filter( array_map('trim', $plugin['br_catalogue']['tmp_entries']['ctlg_id']) ) );
      $plugin['br_catalogue']['entries'][$ekey]['ctge_catalogid'] = $plugin['br_catalogue']['tmp_entries']['ctlg_id'];

      //ctge_tags to array
      $plugin['br_catalogue']['tmp_entries']['ctgry']=$evalue['ctge_tags'];
      $plugin['br_catalogue']['tmp_entries']['ctgry'] = explode("|", trim($plugin['br_catalogue']['tmp_entries']['ctgry']) );
      $plugin['br_catalogue']['tmp_entries']['ctgry'] = array_unique( array_filter( array_map('trim', $plugin['br_catalogue']['tmp_entries']['ctgry']) ) );
      $plugin['br_catalogue']['entries'][$ekey]['ctge_tags'] = $plugin['br_catalogue']['tmp_entries']['ctgry'];

      //unserialize ctge_image
      $plugin['br_catalogue']['entries'][$ekey]['ctge_image'] =	@unserialize($evalue['ctge_image']);

      //unserialize ctge_file
      $plugin['br_catalogue']['entries'][$ekey]['ctge_file'] =	@unserialize($evalue['ctge_file']);

//build google maps
      //global map enabled in cp
      if ($content['br_catalogue']['ctg_usegooglemaps']) {

        //get address array (deprected))
        //$evalue['address'] = @unserialize($evalue['ctge_address']);

        //map enabled in entry?
				if ($evalue['ctge_address_show_map'] == 1) {

					 //should have coordinates now => add js code
					 if ($evalue['ctge_address_long']!=0 && $evalue['ctge_address_lat']!=0)  {
						//custom image

            if ( isset($evalue['ctge_address_marker']) && $evalue['ctge_address_marker'] != '0.gif' && file_exists($phpwcms['modules'][$crow["acontent_module"]]['path'].'template/map-icons/'.$evalue['ctge_address_marker']) ) {
                $markerimg = PHPWCMS_URL.$phpwcms['modules'][$crow["acontent_module"]]['dir'].'template/map-icons/'.$evalue['ctge_address_marker'];
            } else {
                $markerimg = ""; //takes the google marker
            }

						$htmlinfo = '<a href="'.$plugin['br_catalogue']['base_link'].'&amp;ctg_id='.$evalue['ctge_id'].'">'.html_specialchars($evalue['ctge_title']).'</a>';
						$htmlinfo .= '<br />'.html_specialchars($evalue['ctge_address_address']).'<br />'.$evalue['ctge_address_zip'].' '.html_specialchars($evalue['ctge_address_city']);
						$plugin['br_catalogue']['googlemarkercode'] .= getJSNewMarkerCode($evalue['ctge_id'], $evalue['ctge_address_long'], $evalue['ctge_address_lat'], html_specialchars($evalue['ctge_title']),$markerimg,$htmlinfo);

            //calculate new center for map
            if (!isset($ctg_entry_max_lon)) $ctg_entry_max_lon = $evalue['ctge_address_long'];
            if (!isset($ctg_entry_min_lon)) $ctg_entry_min_lon = $evalue['ctge_address_long'];
            if (!isset($ctg_entry_max_lat)) $ctg_entry_max_lat = $evalue['ctge_address_lat'];
            if (!isset($ctg_entry_min_lat)) $ctg_entry_min_lat = $evalue['ctge_address_lat'];

    		    $ctg_entry_max_lon = (float) max($evalue['ctge_address_long'], $ctg_entry_max_lon);
            $ctg_entry_min_lon = (float) min($evalue['ctge_address_long'], $ctg_entry_min_lon);
            $ctg_entry_max_lat = (float) max($evalue['ctge_address_lat'], $ctg_entry_max_lat);
            $ctg_entry_min_lat = (float) min($evalue['ctge_address_lat'], $ctg_entry_min_lat);

					} else {
						//no coordinates
					}

				} //map enabled in entry

			}	//map enabled in cp


//replace images

      //which gallery?
      if ($plugin['br_catalogue']['entries'][$ekey]['ctge_image'][1]['active'] == 1) { //images from folder


        $list_img_temp = '';
        $img_desc = '';
				$img_a = "";
        $rand = 0;

        $ctg_folder_imgs = $plugin['br_catalogue']['entries'][$ekey]['ctge_image'][1];
          /*
          $ctg_folder_imgs['root']
          $ctg_folder_imgs['pag']
          $ctg_folder_imgs['pagnr']
          */
        $folder = opendir($phpwcms['modules'][$crow["acontent_module"]]['path'].$ctg_folder_imgs['root']);

        $pic_types = array("jpg", "jpeg", "gif", "png");
        $pics = array();
        while ($file = readdir ($folder)) {
          if(in_array(substr(strtolower($file), strrpos($file,".") + 1),$pic_types) ) {
            array_push($pics,$file);
          }
        }
        closedir($folder);
        if (count($pics)) {
          if ( $content['br_catalogue']['ctg_imgrand'] ) {
            $rand = rand ( 0 , count($pics)-1 );
          }

if ( $plugin['br_catalogue']['postvars']['tmpl'] >= 2 ){

					$thumb2_image = imagick_converting(
									array(	"target_ext"	=>	strtolower( substr($pics[$rand], -3) ),
											"image_name"	=>	$pics[$rand],
                      "error"            =>    0,
											"max_width"		=>	$content['br_catalogue']['ctg_imgwidth'],
											"max_height"	=>	$content['br_catalogue']['ctg_imgheight'],
                      "image_dir"        =>    $phpwcms['modules'][$crow["acontent_module"]]['path'].$ctg_folder_imgs['root'],
                      "thumb_dir"        =>    PHPWCMS_IMAGES,
                                'jpg_quality'    =>    100,
                                'sharpen_level'    =>    0,
                                'density'        =>    72,
                                'add_command'    =>    '',
											"thumb_name"	=>	md5(	$pics[$rand].$content['br_catalogue']['ctg_imgwidth'].
																		$content['br_catalogue']['ctg_imgheight'].
																		$phpwcms["sharpen_level"].$content['br_catalogue']['ctg_imgcrop']),
                      "crop_image"	=>	$content['br_catalogue']['ctg_imgcrop']
										  )
										);

						//html image
						$list_img_temp  = '<img src="'.PHPWCMS_IMAGES.$thumb2_image["thumb_name"].'" ';
						$list_img_temp .= 'height="'.$thumb2_image['max_height'].'" width="'.$thumb2_image['max_width'].'" alt="" border="0" />';
} else {

          //$thmbname = $pics[$rand].'.thumb.'.strtolower(substr($pics[$rand], -3));
          $thmbname = $pics[$rand];
          //$thumb_image = getimagesize ($phpwcms['modules'][$crow["acontent_module"]]['dir'].$ctg_folder_imgs['root'].'thumbs/' . $thmbname);
    			$list_img_temp  = '<img src="'.$phpwcms['modules'][$crow["acontent_module"]]['dir'].$ctg_folder_imgs['root'].'thumbs/tmblst_'.$crow['acontent_id'].'_'.$thmbname.'" ';
    			//$list_img_temp  .= 'width="'.$content['br_catalogue']['ctg_imgwidth'].'" height="'.$content['br_catalogue']['ctg_imgheight'].'" ';
    			$list_img_temp .= 'alt="" border="0" />';
}
        }


      } else { //phpwcms images

        $ctg_phpwcms_imgs = $plugin['br_catalogue']['entries'][$ekey]['ctge_image'][0];
          /*
          $ctg_phpwcms_imgs['width']
          $ctg_phpwcms_imgs['height']
          $ctg_phpwcms_imgs['crop']
          $ctg_phpwcms_imgs['zoom']
          $ctg_phpwcms_imgs['data'];
          */

        $list_img_temp = '';
        $img_desc = '';
				$img_a = "";
        $rand = 0;
        //randomize if necessary an get one image for listing
        if ( $content['br_catalogue']['ctg_imgrand'] && count($ctg_phpwcms_imgs['data']) ) {
          $rand = rand ( 0 , count($ctg_phpwcms_imgs['data'])-1 );
        }
        $image_info = isset($ctg_phpwcms_imgs['data'][$rand]) ? $ctg_phpwcms_imgs['data'][$rand] : 0;

        if (is_array($image_info)) {

					//build html img-tag
					//get image
					// 0   :1       :2   :3        :4    :5     :6      :7       :8
					// dbid:filename:hash:extension:width:height:caption:position:zoom
					$thumb_image = get_cached_image(
									array(	"target_ext"	=>	$image_info['f_ext'],
											"image_name"	=>	$image_info['f_hash'] . '.' . $image_info['f_ext'],
											"max_width"		=>	$content['br_catalogue']['ctg_imgwidth'],
											"max_height"	=>	$content['br_catalogue']['ctg_imgheight'],
											"thumb_name"	=>	md5(	$image_info['f_hash'].
																		$content['br_catalogue']['ctg_imgwidth'].
																		$content['br_catalogue']['ctg_imgheight'].
																		$phpwcms["sharpen_level"].$content['br_catalogue']['ctg_imgcrop']),
                      "crop_image"	=>	$content['br_catalogue']['ctg_imgcrop']
										  )
										);


					if($thumb_image != false) {

						$img_desc = $image_info['caption'];

						//html image
						$list_img_temp  = '<img src="'.PHPWCMS_IMAGES.$thumb_image[0].'" ';
						$list_img_temp .= $thumb_image[3].' alt="'.$img_desc.'" border="0" />';
					}

        }

      } //end phpwcms images


			//get detail template
			$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = $plugin['br_catalogue']['tmpl']['list_entry'];

			//build link to detailsview
			$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = str_replace('{CATALOG_LINK}', $plugin['br_catalogue']['no_entry'] ? '#' : $plugin['br_catalogue']['base_link'].'&amp;ctg_id='.$evalue['ctge_id'], $plugin['br_catalogue']['tmpl']['single_entry'][$ekey]);

      //add entry to menu (filter 0)
        foreach ( $plugin['br_catalogue']['filter'][0]['tags'] as $key => $val) {
          if ( in_array($val['id'], $plugin['br_catalogue']['entries'][$ekey]['ctge_catalogid']) ) {
            $menu['id'] = $plugin['br_catalogue']['entries'][$ekey]['ctge_id'];
            $menu['title'] = $plugin['br_catalogue']['entries'][$ekey]['ctge_title'];
            $menu['image'] = $list_img_temp; //the first or random image
            $menu['ekey'] = $ekey; //with ekey we get access to this template part later on
            $plugin['br_catalogue']['filter'][0]['tags'][$key]['entries'][] = $menu;
          }
        }
      //add entry to menu (filter 1)
        foreach ( $plugin['br_catalogue']['filter'][1]['tags'] as $key => $val) {
          if ( in_array($val['name'], $plugin['br_catalogue']['entries'][$ekey]['ctge_tags']) ) {
            $menu['id'] = $plugin['br_catalogue']['entries'][$ekey]['ctge_id'];
            $menu['title'] = $plugin['br_catalogue']['entries'][$ekey]['ctge_title'];
            $menu['image'] = $list_img_temp; //the first or random image
            $menu['ekey'] = $ekey; //with ekey we get access to this template part later on
            $plugin['br_catalogue']['filter'][1]['tags'][$key]['entries'][] = $menu;
          }
        }

			//replace IMAGE
			$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = render_cnt_template($plugin['br_catalogue']['tmpl']['single_entry'][$ekey], 'IMAGE', $list_img_temp);
			$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = render_cnt_template($plugin['br_catalogue']['tmpl']['single_entry'][$ekey], 'IMAGE_DESC', html_specialchars($img_desc));

			//replace title + text
      //delete all html tags
      //$evalue['ctge_text'] = '<span class="ctg_list_text">'.preg_replace('/^<p[^>]*>(.*?)<\/p>$/is', '$1', $evalue['ctge_text']).'</span>';
      if (isset($content['br_catalogue']['ctg_listhtml']) && $content['br_catalogue']['ctg_listhtml'] == 1) {
        $evalue['ctge_text'] = ctg_combinedParser($evalue['ctge_text']);
      }

			$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = render_cnt_template($plugin['br_catalogue']['tmpl']['single_entry'][$ekey], 'TITLE', html_specialchars($evalue['ctge_title']));
			$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = render_cnt_template($plugin['br_catalogue']['tmpl']['single_entry'][$ekey], 'TEXT', $evalue['ctge_text']);
			$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = render_cnt_template($plugin['br_catalogue']['tmpl']['single_entry'][$ekey], 'TITLE2', html_specialchars($evalue['ctge_title2']));
			$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = render_cnt_template($plugin['br_catalogue']['tmpl']['single_entry'][$ekey], 'TEXT2', $evalue['ctge_text2']);
			$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = render_cnt_template($plugin['br_catalogue']['tmpl']['single_entry'][$ekey], 'CATALOG_ID', html_specialchars($evalue['ctge_id']));

    	$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = render_cnt_template($plugin['br_catalogue']['tmpl']['single_entry'][$ekey], 'ADDRESS', html_entities($evalue['ctge_address_address']));
    	$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = render_cnt_template($plugin['br_catalogue']['tmpl']['single_entry'][$ekey], 'ZIP', html_entities($evalue['ctge_address_zip']));
    	$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = render_cnt_template($plugin['br_catalogue']['tmpl']['single_entry'][$ekey], 'CITY', html_entities($evalue['ctge_address_city']));
    	$plugin['br_catalogue']['tmpl']['single_entry'][$ekey] = render_cnt_template($plugin['br_catalogue']['tmpl']['single_entry'][$ekey], 'COUNTRY', html_entities($evalue['ctge_address_country']));

//replace FILTER_TAGS
      $plugintmp_tags = array();
      //$plugintmp_tags = explode("|", trim($ekey["ctge_tags"], "|") );
      $plugintmp_tags = $plugin['br_catalogue']['entries'][$ekey]["ctge_tags"];
      for ($i=1;$i<=4 ;$i++ ) {
      	$filtertags1 = array();
        $filtertags1 = array_intersect($plugintmp_tags,$plugin['br_catalogue']['filter'][$i]['array']);
        $plugin['br_catalogue']['tmpl']['single_entry'][$ekey]	= render_cnt_template($plugin['br_catalogue']['tmpl']['single_entry'][$ekey], 'FILTER'.$i.'_TAGS', html_entities(implode(', ', $filtertags1)));
      }

			//Add the content for later output
			$plugin['br_catalogue']['list']	.= $plugin['br_catalogue']['tmpl']['single_entry'][$ekey];
			$plugin['br_catalogue']['list']	.= $plugin['br_catalogue']['tmpl']['list_spacer'];

		}	//end foreach loop
	}	//end if no entry

  unset($plugin['br_catalogue']['tmp_entries']);

//global google maps activated ? add js-init-code
	if ($content['br_catalogue']['ctg_usegooglemaps']) {
    //default position = somewhere in germany
    if (!isset($ctg_entry_max_lon)) $ctg_entry_max_lon  = 8;
    if (!isset($ctg_entry_min_lon)) $ctg_entry_min_lon  = 8;
    if (!isset($ctg_entry_max_lat)) $ctg_entry_max_lat  = 52;
    if (!isset($ctg_entry_min_lat)) $ctg_entry_min_lat  = 52;
    $ctg_entry_center_lon = (float) ($ctg_entry_min_lon + $ctg_entry_max_lon) / 2;
    $ctg_entry_center_lat = (float) ($ctg_entry_min_lat + $ctg_entry_max_lat) / 2;

    //get initial code
    $plugin['br_catalogue']['googlejscode'] = getJSInitCodeGoogleMaps( floatval($ctg_entry_center_lat), floatval($ctg_entry_center_lon) );
    //add the marker js
    $plugin['br_catalogue']['googlejscode'] .= $plugin['br_catalogue']['googlemarkercode'];
  }

  //for filter 0 + 1 render divs and add to filter listing
  for ($i=0; $i < 2; $i++ ) {

    if($plugin['br_catalogue']['filter'][$i]['render'] == 'js') {

      //we need js here
      initJSLib();

      $mod_ctg_listing = '';
      $mod_ctg_listing .= ' <div class="ctg_jslist_content">'.LF; //issue17

      foreach($plugin['br_catalogue']['filter'][$i]['tags'] as $k => $value) {

        //yet here to get the number
        $j=0;
        $mod_ctg_listing_tmp_entries = '';
        foreach($value['entries'] as $kk => $vv) {
          //we add the already rendered template entry (ekey))
          $mod_ctg_listing_tmp_entries .= $plugin['br_catalogue']['tmpl']['single_entry'][$vv['ekey']];
          $j++;
        }
        //$mod_ctg_listing .= ' <div class="ctg_jslist_content">'.LF; //issue17
        $mod_ctg_listing .= ' <div class="ctg_jslist_wrapper">'.LF;
        $mod_ctg_listing  .= '    <div class="ctg_jslist_headline';
        if ( $value['id']== $plugin['br_catalogue']['filter'][$i]['postvars'] ) {
          //$mod_ctg_listing  .= '_active'; //should be done by js
        }
        $mod_ctg_listing .= '">';
        $mod_ctg_listing .= '<h3 class="ctg_jslist_toggle_entries ">'.$value['name'].' <span class="ctg_headline_number">('.$j.')</span></h3>';
        $mod_ctg_listing .= '</div>'.LF;
        $mod_ctg_listing  .= '    <div class="ctg_jslist_items">'.LF;
        //add all entries
        $mod_ctg_listing  .= $mod_ctg_listing_tmp_entries;
        $mod_ctg_listing .= LF.'    </div>'.LF;
        $mod_ctg_listing .= ' </div>'.LF; //close wrapper
      }
      $mod_ctg_listing .= ' </div>'.LF; //close ctg_jslist_content
      //add to filter listing
      $plugin['br_catalogue']['filter'][$i]['listing'] = $mod_ctg_listing;

      //if filter renders as 'div' then the listing with the entries is part of the filter output
      //therefore we delete the rendered standard listing
			$plugin['br_catalogue']['list'] = "";

    } elseif ($plugin['br_catalogue']['filter'][$i]['render'] == 'div') {

       $mod_ctg_listing = '<div class="ctg_divlist_content">';

        foreach($plugin['br_catalogue']['filter'][$i]['tags'] as $k => $value) {

          //yet here to get the number
          $j=0;
          $mod_ctg_listing_tmp_entries = "";
          foreach($value['entries'] as $kk => $vv) {
            //we add the already rendered template entry (ekey)) - they get the html from the template
            $mod_ctg_listing_tmp_entries .= $plugin['br_catalogue']['tmpl']['single_entry'][$vv['ekey']];
            $j++;
          }

          $mod_ctg_listing .= ' <div class="ctg_divlist_category">'.LF;
          $mod_ctg_listing .= '  <div class="ctg_divlist_category_headline">';
          $mod_ctg_listing .= '   <h3>'.$value['name'].' <span class="ctg_headline_number">('.$j.')</span></h3>'.LF;
          $mod_ctg_listing .= '  </div>'.LF;
          $mod_ctg_listing .= '  <div class="ctg_divlist_items">'.LF;
          //add all entries
          $mod_ctg_listing  .= $mod_ctg_listing_tmp_entries;
          $mod_ctg_listing .= LF.'  </div>'.LF; //close ctg_list_items
          $mod_ctg_listing .= ' </div>'.LF; //close ctg_list_category
        } // end foreach

        $mod_ctg_listing .= '</div>'.LF; //close ctg_list_content
        //add to filter listing
        $plugin['br_catalogue']['filter'][$i]['listing'] = $mod_ctg_listing;

        //if filter renders as 'div' then the listing with the entries is part of the filter output
        //therefore we delete the rendered standard listing
  			$plugin['br_catalogue']['list'] = "";
    }

  } //end for

  //replace filters + searchword
	$plugin['br_catalogue']['tmpl']['list_head']	= render_cnt_template($plugin['br_catalogue']['tmpl']['list_head'], 'SEARCHTEXT', $plugin['br_catalogue']["postvars"]["search"]);
	$plugin['br_catalogue']['tmpl']['list_head']	= render_cnt_template($plugin['br_catalogue']['tmpl']['list_head'], 'FILTER_2', $plugin['br_catalogue']['filter'][2]['listing']);
	$plugin['br_catalogue']['tmpl']['list_head']	= render_cnt_template($plugin['br_catalogue']['tmpl']['list_head'], 'FILTER_3', $plugin['br_catalogue']['filter'][3]['listing']);
	$plugin['br_catalogue']['tmpl']['list_head']	= render_cnt_template($plugin['br_catalogue']['tmpl']['list_head'], 'FILTER_4', $plugin['br_catalogue']['filter'][4]['listing']);

//add js if needed
	if ( !$plugin['br_catalogue']['no_entry'] && ( $plugin['br_catalogue']['filter'][0]['render'] == 'js' || $plugin['br_catalogue']['filter'][1]['render'] == 'js' ) ) {

    // generate js-code for category slider
    //mootools
    if($plugin['br_catalogue']['jslib'] == "mootools") {

				$jscode = " window.addEvent( 'domready',function(){".LF.
													"    $$( '.ctg_jslist_wrapper' ).each(function(item){".LF.
													"      var thisSlider = new Fx.Slide( item.getElement( '.ctg_jslist_items' ), { duration: 350 } );".LF.
													"      thisSlider.hide();".LF.
													"      item.getElement( '.ctg_jslist_toggle_entries' ).addEvent( 'click', function(){".LF.
													"        thisSlider.toggle();".LF.
													"        item.getElement( '.ctg_jslist_toggle_entries' ).toggleClass ('ctg_jslist_toggle_entries_active');".LF.
													"      });".LF.
													"    });".LF.
												  " });".LF;

    } elseif ($plugin['br_catalogue']['jslib']=="jquery") { //jquery

        $jscode = " $(document).ready(function() {
    $('.ctg_jslist_items').hide();
      $('.ctg_jslist_headline').click(function(aa) {
        $(this).next().height($(this).next().height());
        $(this).next().slideToggle('slow', function() {
          $(this).prev().children().toggleClass('ctg_jslist_toggle_entries_active');
      });
    });
  });".LF;

    }

    //add js-code to output
		$plugin['br_catalogue']['list'] .= '<script type="text/javascript">'.LF.'<!-- '.LF.$jscode.LF.' //-->'.LF.'</script>'.LF;

	} //js slider


	//add header and footer
	$plugin['br_catalogue']['list'] = $plugin['br_catalogue']['tmpl']['list_head'].	$plugin['br_catalogue']['list'] . $plugin['br_catalogue']['tmpl']['list_footer'];


	//replace global tags
	$plugin['br_catalogue']['list'] = str_replace('{BACKLINK}', $plugin['br_catalogue']['base_link'], $plugin['br_catalogue']['list']);

  //replace filter 1 + 0 here cause they don't have to be in the header (not within the form)
	$plugin['br_catalogue']['list']	= str_replace('{FILTER_0}', $plugin['br_catalogue']['filter'][0]['listing'], $plugin['br_catalogue']['list']);
	$plugin['br_catalogue']['list']	= str_replace('{FILTER_1}', $plugin['br_catalogue']['filter'][1]['listing'], $plugin['br_catalogue']['list']);

  //replace rss link
	$plugin['br_catalogue']['list']	= str_replace('{RSS}', PHPWCMS_URL.CONTENT_PATH.'rss/feed-catalog-'.$crow["acontent_aid"].'-'.$crow['acontent_id'].'.xml', $plugin['br_catalogue']['list']);


	//Add global map if activated
	if ($content['br_catalogue']['ctg_usegooglemaps']) {
		$plugin['br_catalogue']['map'] = '<div id="map_canvas" class="mapcontainer">This should be a map.</div>'.LF.'<script type="text/javascript">'.LF.'<!-- '.LF.$plugin['br_catalogue']['googlejscode'].LF.' //-->'.LF.'</script>'.LF.'<noscript>You need to enable JavaScript in order to use google maps!</noscript>'.LF;
		//render map contents
	}
	$plugin['br_catalogue']['list'] = render_cnt_template($plugin['br_catalogue']['list'], 'MAP', $plugin['br_catalogue']['map'] );

//add global replacements
  $plugin['br_catalogue']['list']	= render_cnt_template($plugin['br_catalogue']['list'], 'FILTER_STRING', html_entities($plugin['br_catalogue']['filterstring']));

//display list
	$CNT_TMP .= $plugin['br_catalogue']['list'];

  } //end listing

} //end no active catalogs

unset($plugin['br_catalogue']['ctg_id']);
// render content part title/subtitle
$CNT_TMP = render_cnt_template($CNT_TMP, 'CP_TITLE', html_specialchars($crow['acontent_title']));
$CNT_TMP = render_cnt_template($CNT_TMP, 'CP_SUBTITLE', html_specialchars($crow['acontent_subtitle']));
$CNT_TMP = "<!-- Catalogue Module Start//-->".LF.$CNT_TMP.LF."<!-- Catalogue Module End//-->";
?>